import optparse
import os
import sys

from orioluspith.publicator import version
from orioluspith.publicator.storer import Storer, StorerError

def exit(parser):
    parser.print_help()
    parser.destroy()
    sys.exit(2)

def run():
    usage = """usage: oripub [options] path url"""

    parser = optparse.OptionParser(usage=usage, version = "oripub %s" % version)
    
    parser.add_option("-n", "--no-sign", dest = "no_sign", action = "store_true", default = False, help = "option that disable signing packet")
    parser.add_option("-r", "--keyring", dest = "keyring", help = "path to keyring")
    parser.add_option("-s", "--secret-keyring", dest = "secret_keyring", help = "path to secret keyring")
    parser.add_option("-p", "--key-password", dest = "password", help = "password for default key into secret_keyring")
    parser.add_option("-o", "--output-path", dest = "output_path", help = "path to output directory")
    parser.add_option("-l", "--packetlist-path", dest = "packetlist_path", help = "path to packetlist for initialize")
    parser.add_option("-u", "--packetlist-url", dest = "packetlist_url", help = "url to repository for download init packetlist")
    
    (options, args) = parser.parse_args()

    if len(args) != 2:
        exit(parser)

    if options.output_path:
        output_path = options.output_path
    else:
        output_path = "."
        
    packetlist_path = None
    if options.packetlist_path:
        packetlist_path = options.packetlist_path

    packetlist_url = None
    if options.packetlist_url:
        packetlist_url = options.packetlist_url
        
    keyring = None
    if options.keyring:
        keyring = options.keyring

    secret_keyring = None
    if options.secret_keyring:
        secret_keyring = options.secret_keyring

    password = None
    if options.password:
        password = options.password

    packet_path = args[0]
    base_url = args[1]
    try:
        storer = Storer(output_path, packet_list_path = packetlist_path, remote_packet_list_url = packetlist_url, keyring = keyring, secret_keyring = secret_keyring)
        if options.no_sign:
            storer.add_packet(packet_path, base_url)
        else:
            storer.add_packet(packet_path, base_url, sign = True, password = password)
        if os.path.isdir(packet_path):
            print "Packets from dir '%s' were added to packetlist" % packet_path
        else:
            print "Packet '%s' was added to packetlist" % packet_path
    except StorerError, message:
        print message

if __name__ == "__main__":
    run()
